package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cssl.pojo.User;
import com.cssl.service.UserService;
import com.cssl.utils.MD5Utils;
import com.cssl.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UserController {
    @Autowired
    private UserService service;

    @Autowired
    private RedisUtil redisUtil;

    //注册
    @RequestMapping("/regist")
    public boolean regist(@RequestParam Map<String,Object> map) throws ParseException {
        User u = new User();
        u.setEmail(map.get("email").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date born = sdf.parse(map.get("born").toString());
        u.setBorndate(born);
        u.setPhone(map.get("phone").toString());
        u.setUsername(map.get("username").toString());
        u.setSex(map.get("sex").toString());
        u.setFaddress(map.get("adrs").toString());
        u.setPassword(MD5Utils.inputPassToFormPass(map.get("pwd").toString()));
        return service.save(u);
    }

     //验证登录用户是否在线
     @RequestMapping("/useronline")
     public Boolean useronline(User user){
         List<User> user1 = new ArrayList<>();
         //暂时定为100
         List<Object> list = redisUtil.lRange("users",0,100);//拿出users
         System.out.println("list:"+list);
         if(list.size() != 0){
             //拿出redis集合项存入users
             for (Object o:list) {
                 if (o instanceof User){
                     user1.add((User) o);
                 }
             }
             System.out.println("users:"+user1);
             System.out.println("user:"+user);
             for (User u:user1) {
                 //判断是否同一用户
                 if (u.getUsername().equals(user.getUsername())  && u.getPassword().equals(user.getPassword()) ){
                     //在线
                     return true;
                 }
             }
         }
        return false;
     }

    //用户登录 储存
    @RequestMapping("/login")
    public Boolean login(User user, HttpServletRequest request){
        //存放user集合
        List<User> user1 = new ArrayList<>();
        //暂时定为100
        List<Object> list = redisUtil.lRange("users",0,100);
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUsername,user.getUsername());
        lqw.eq(User::getPassword,MD5Utils.inputPassToFormPass(user.getPassword()));
        lqw.eq(User::getIsadmin,user.getIsadmin());
        User users = service.getOne(lqw);
        if(users != null){
            //拿出redis集合项存入users
            for (Object o:list) {
                if (o instanceof User){
                    user1.add((User) o);
                }
            }
            //存入redis 集合list
            user1.add(users);
            //存储单个用户
            if(user.getIsadmin() == 0){
                HttpSession session =request.getSession();
                System.out.println("sessionid:==="+session.getId());
                redisUtil.set(session.getId(),users,24*60*60L);//存储当前登录用户
            }else{
                redisUtil.set("admin",users,24*60*60L);//存储当前登录用户
            }
            //存储在线用户集合
            redisUtil.remove("users");//删除原先users
            redisUtil.rPushAll("users",user1,60*60*24);
           HttpSession session = request.getSession();
           session.setAttribute("user",user);
            return true;
        }
        return false;
    }
    //验证用户
    @RequestMapping("/yzlogin")
    public Boolean yzlogin(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)redisUtil.get(session.getId());
        if (user != null)
            return true;
        return false;
    }

    //注销
    @RequestMapping("/remove")
    public boolean remove(HttpServletRequest request){
        //redis对象集合转换为user存储集合
        List<User> user1 = new ArrayList<>();
        //注销用户后其他在线用户集合
        List<User> user2 = new ArrayList<>();
        HttpSession session = request.getSession();
        User user = (User)redisUtil.get(session.getId());
        List<Object> list = redisUtil.lRange("users",0,100);
        for (Object o:list) {
            if (o instanceof User){
                user1.add((User) o);
            }
        }
        System.out.println("user1"+user1);
        for (User u:user1) {
            //判断是否同一用户
            if (!user.getUsername().equals(u.getUsername())){
              user2.add(u);
            }
        }
        redisUtil.remove(session.getId());
        redisUtil.remove("users");
        //存储在线用户集合
        if (user2.size() > 0) {
            redisUtil.rPushAll("users", user2, 60 * 60 * 24);
        }
        return true;
    }

    //我的信息
    @RequestMapping("/myinfo")
    public User myinfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUid,user.getUid());
        return service.getOne(lqw);
    }

    //修改 用户信息  上传图片
    @RequestMapping("/updateinfo1")
    public Boolean updateinfo1(@RequestParam MultipartFile files,@RequestParam Map<String, Object> map)
            throws IllegalStateException, IOException, ParseException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println(map);
        String username = map.get("username").toString();
        String sex = map.get("sex").toString();
        String phone = map.get("phone").toString();
        String email = map.get("email").toString();
        String address = map.get("faddress").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("borndate").toString());
        User user = new User();
        user.setUsername(username);
        user.setBorndate(date);
        user.setEmail(email);
        user.setFaddress(address);
        user.setPhone(phone);
        user.setSex(sex);
        user.setUid(u.getUid());
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        user.setFilename(fileName);
        if (types.contains(type) && size <= 3) {
            System.out.println("user:"+user);
           files.transferTo(new File(path + fileName));
           Boolean bl = service.updateById(user);
            if(bl){
                //redis对象集合转换为user存储集合
                List<User> user1 = new ArrayList<>();
                //注销用户后其他在线用户集合
                List<User> user2 = new ArrayList<>();
                List<Object> list = redisUtil.lRange("users",0,100);
                for (Object o:list) {
                    if (o instanceof User){
                        user1.add((User) o);
                    }
                }
                for (User u2:user1) {
                    //判断是否同一用户
                    if (user.getUid() == u2.getUid()){
                        continue;
                    }
                    user2.add(u2);
                }
                user2.add(service.getById(user.getUid()));
                redisUtil.remove(session.getId());
                redisUtil.set(session.getId(),service.getById(user.getUid()));
                redisUtil.remove("users");
                //存储在线用户集合
                if (user2.size() > 0) {
                    redisUtil.rPushAll("users", user2, 60 * 60 * 24);
                }
                return true;
            }



        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //修改用户信息
    @RequestMapping("/updateinfo2")
    public Boolean updateinfo2(@RequestParam Map<String, Object> map,HttpServletRequest request)
            throws IllegalStateException, ParseException {
        // 从请求上下文里获取Request对象
        HttpSession session = request.getSession();
        User u =(User)redisUtil.get(session.getId());
        System.out.println(map);
        String username = map.get("username").toString();
        String sex = map.get("sex").toString();
        String phone = map.get("phone").toString();
        String email = map.get("email").toString();
        String address = map.get("faddress").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("borndate").toString());
        User user = new User();
        user.setUsername(username);
        user.setBorndate(date);
        user.setEmail(email);
        user.setFaddress(address);
        user.setPhone(phone);
        user.setSex(sex);
        user.setUid(u.getUid());
        Boolean bl = service.updateById(user);
        if(bl){
                //redis对象集合转换为user存储集合
                List<User> user1 = new ArrayList<>();
                //注销用户后其他在线用户集合
                List<User> user2 = new ArrayList<>();
                List<Object> list = redisUtil.lRange("users",0,100);
                for (Object o:list) {
                    if (o instanceof User){
                        user1.add((User) o);
                    }
                }
                for (User u2:user1) {
                    //判断是否同一用户
                    if (user.getUid() == u2.getUid()){
                        continue;
                    }
                    user2.add(u2);
                }
                user2.add(service.getById(user.getUid()));
                redisUtil.remove(session.getId());
                redisUtil.set(session.getId(),service.getById(user.getUid()));
                redisUtil.remove("users");
                //存储在线用户集合
                if (user2.size() > 0) {
                    redisUtil.rPushAll("users", user2, 60 * 60 * 24);
                }
                return true;
            }
        return false;
    }


    //修改密码
    @RequestMapping("/updatepwd")
    public Boolean updatepwd(@RequestParam String password,HttpServletRequest request){
        HttpSession session = request.getSession();
        User u = (User) redisUtil.get(session.getId());//拿到redis存储登录用户
        User user = new User();
        user.setUid(u.getUid());
        user.setPassword(MD5Utils.inputPassToFormPass(password));
        Boolean bl = service.updateById(user);
        if (bl){
            //拿到修改后的user
            User xguser =service.getById(u.getUid());
            //redis对象集合转换为user存储集合
            List<User> user1 = new ArrayList<>();
            //注销用户后其他在线用户集合
            List<User> user2 = new ArrayList<>();
            List<Object> list = redisUtil.lRange("users",0,100);
            for (Object o:list) {
                if (o instanceof User){
                    user1.add((User) o);
                }
            }
            for (User u1:user1) {
                //判断是否同一用户
                if (!u.getUsername().equals(u1.getUsername())){
                    user2.add(u1);
                }
            }
            user2.add(xguser);//添加修改后的user至user2
            redisUtil.remove(session.getId());//删除redis原有登录用户
            redisUtil.set(session.getId(),xguser);//创建存储登录用户
            redisUtil.remove("users");
            //存储在线用户集合
            if (user2.size() > 0) {
                redisUtil.rPushAll("users", user2, 60 * 60 * 24);
            }
            return true;
        }
        return false;
    }

    //验证旧密码
    @RequestMapping("/yzpwd")
    public Boolean yzpwd(@RequestParam String password,HttpServletRequest request){
        HttpSession session = request.getSession();
        User u = (User) redisUtil.get(session.getId());
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUid,u.getUid());
        lqw.eq(User::getPassword,MD5Utils.inputPassToFormPass(password));
        User us =service.getOne(lqw);
        if (us != null){
            return true;
        }
        return false;
    }

    //单个用户详情
    @RequestMapping("/userdetail")
    public User userdetail(@RequestParam Integer uid,HttpServletRequest req){
        HttpSession session = req.getSession();
        User u = (User)redisUtil.get(session.getId());
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        if (uid ==0){
            lqw.eq(User::getUid,u.getUid());
        }else{
            lqw.eq(User::getUid,uid);
        }
        return service.getOne(lqw);
    }

}
